package com.zwz.utils;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

@Component
public class TcpServer implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments args) throws Exception {
        new  Thread(this::initServer).start();
    }

    public static boolean guanhaoCorrectStatus;
    public static boolean boxCodeInferStatus;

    @Resource
    private Environment environment;

    private static int PORT;
    private static String targetIP;
    private static int targetPort;


    public void initServer(){
        PORT = Integer.parseInt(Objects.requireNonNull(environment.getProperty("listenPort")));
        targetIP = environment.getProperty("targetIP");
        targetPort = Integer.parseInt(Objects.requireNonNull(environment.getProperty("targetPort")));
        listenServer();
    }


    public void listenServer(){
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("服务器已启动，正在监听端口 " + PORT + "...");

            while (true) {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端连接创建一个新线程处理
                new Thread(new ClientHandler(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器异常: " + e.getMessage());
        }
    }

    // 处理客户端连接的内部类
    private static class ClientHandler implements Runnable {
        private final Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()))) {

                String inputLine;
                // 读取客户端发送的数据
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("收到来自 " + clientSocket.getInetAddress().getHostAddress()
                            + " 的消息: " + inputLine);

                    // 这里可以添加处理逻辑或回复客户端的代码
                    if (guanhaoCorrectStatus) {
                        inputLine = MessageUtil.GuanhaoCorrect(inputLine);

                    }
                    if (boxCodeInferStatus) {
                        inputLine = MessageUtil.BoxCodeInfer(inputLine);
                    }
                    TcpClient.sendAsync(targetIP, targetPort, inputLine);
                }
            } catch (IOException e) {
                System.err.println("处理客户端连接时出错: " + e.getMessage());
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    System.err.println("关闭客户端连接时出错: " + e.getMessage());
                }
                System.out.println("客户端已断开: " + clientSocket.getInetAddress().getHostAddress());
            }
        }
    }
}
